"""
Main Active Connections program

"""
import commands
from pyfpdf import fpdf
from support import pdf as pdfData
import argparse


class ActivePorts:
	"""
	Stores Currenty Listening Ports and Connections
	
	Keyword arguments:
    Protocol -- TCP or TCP6
    port -- Listening Port
	service -- Active Service
	"""
	def __init__(self, protocol, port, service):
		"""Default Constructor"""
		self.protocol = protocol
		self.port = port
		self.service = service
		self.connections = []
		
	def __str__(self):
		"""String Output"""
		return "Protocol " + self.protocol + "\tIp.port: " + self.port + " service: " + self.service + " Connects: " + str(len(self.connections))
		
	def printData(self):
		"""Prints Data to Stdout"""
		print "Service: " + self.service
		print "Port: " + self.port
		print "Protocol: " + self.protocol
		print "Connected IP's:"
		for x in self.connections:
			print x
		print "\n"

class MachineConnections:
	"""Gets listening ports on localhost and it's connections"""
	def __init__(self):
		"""Default Constructor"""
		self.lista = []
		
	def PortListening(self):
		"""Gets Listening Ports"""
		portlistening = commands.getoutput("/bin/netstat -lnp | grep -w 'LISTEN'").split('\n')	
		return portlistening

	def Connections(self):
		"""Gets Listening Ports"""
		connections =  commands.getoutput("/bin/netstat -nap | grep -w 'ESTABLISHED'").split('\n')	
		return connections

	def crialista(self):
		"""Creates a list with the Active Ports"""
		interfaces = self.PortListening()
		for x in interfaces:
			if not 'No info could be read for' in x:
				a=x.split()
				try:
					service = a[6].split('/')[1]
				except:
					service = 'Unknown'
				y = ActivePorts(a[0],a[3].split(':')[-1],service)
				self.lista.append(y)

		conn = self.Connections()
		
		for x in conn:
			if not 'No info could be read for' in x:
				try:
					a=x.split()
					protocol = a[0]
					port = a[3].split(':')[-1]
					ip=a[4].split(':')[0]
					serv=a[6].split('/')[1].split(':')[0]
					error = False
				except:
					serv='Unknown'
					error = True
				
				if not error:
					for y in self.lista:
						if ((protocol == y.protocol) & (port == y.port) & (serv == y.service)):
							y.connections.append(ip)

	def outputToCmd(self):
		"""Outputs data to stdout"""
		print "Active Connections and Listening Ports:"
		print "Number of Listening Ports: " + str(len(self.lista))
		print "\nDetails:\n"			
		for x in self.lista:
			if x.connections:
				x.printData()
	
	def outputToPdf(self):
		"""Saves data to PDF"""
		#pdf = fpdf.FPDF()
		
		pdf = pdfData.MyPDF()
		pdf.alias_nb_pages()
		pdf.add_page()
		pdf.set_font("Arial", size=18)
		pdf.cell(200, 10, txt="Active Connections and Listening Ports:", align="C")
		pdf.set_font("Arial",'B',12)
		pdf.write(12,'Number of Listening Ports: '+ str(len(self.lista)))
		pdf.write(12,'\nDetails:\n')
		pdf.set_font("Arial", size=10)
		for x in self.lista:
			pdf.write(5,"Service: " + x.service)
			pdf.write(5,"\nPort: " + x.port)
			pdf.write(5,"\nProtocol: " + x.protocol)
			pdf.write(5,"\nConnected IP's:\n")
			if x.connections:
				for y in x.connections:
					pdf.write(5,y+"\n")
			pdf.write(5,"\n")
		# ADD MOAR STUFF!!	
		pdf.output(args.pdf[0])


def main():
	"""Main Function"""
	parser = argparse.ArgumentParser(description='Active Connections')
	parser.add_argument("--pdf", help="directs output to PFD File",default = False , nargs=1,metavar=('PDF File Location'))
	args = parser.parse_args()


	a = MachineConnections()
	a.crialista()
	if not args.pdf:
		a.outputToCmd()
	else:
		a.outputToPdf()

if  __name__ =='__main__':main()

